package com.ErpCoreWeb.Workflow;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CCompany;
import com.ErpCoreModel.Base.CRole;
import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.Workflow.ActivesType;
import com.ErpCoreModel.Workflow.CActivesDef;
import com.ErpCoreModel.Workflow.CActivesDefMgr;
import com.ErpCoreModel.Workflow.CLink;
import com.ErpCoreModel.Workflow.CWorkflowDef;
import com.ErpCoreModel.Workflow.enumApprovalResult;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class AddWorkflowDef
 */
@WebServlet("/AddWorkflowDef")
public class AddWorkflowDef extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

	public CUser m_User = null;
    public CCompany m_Company = null; 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddWorkflowDef() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
        m_User=(CUser)request.getSession().getAttribute("User");
        if (!m_User.IsRole("管理员"))
        {
        	try {
				response.getWriter().print("没有管理员权限！");
	        	response.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	return ;
        }
			String B_Company_id = request.getParameter("B_Company_id");
			if (Global.IsNullParameter(B_Company_id))
				m_Company = Global.GetCtx(this.getServletContext())
						.getCompanyMgr().FindTopCompany();
			else
				m_Company = (CCompany) Global.GetCtx(this.getServletContext())
						.getCompanyMgr().Find(Util.GetUUID(B_Company_id));
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetActivesData"))
        {
        	GetActivesData();
            return ;
        }
        else if (Action.equalsIgnoreCase("Cancel"))
        {
            GetWorkflowDef().Cancel();
            request.getSession().setAttribute("AddWorkflowDef",null);
            return ;
        }
        else if (Action.equalsIgnoreCase("GetLinkData"))
        {
        	GetLinkData();
            return ;
        }
        else if (Action.equalsIgnoreCase("DeleteActivesDef"))
        {
        	DeleteActivesDef();
            return ;
        }
        else if (Action.equalsIgnoreCase("SelectTable"))
        {
        	SelectTable();
            return ;
        }
        else if (Action.equalsIgnoreCase("DeleteLink"))
        {
        	DeleteLink();
            return ;
        }
        else if (Action.equalsIgnoreCase("PostData"))
        {
        	PostData();
            return ;
        }
	}

    void GetActivesData()
    {
        CWorkflowDef WorkflowDef = GetWorkflowDef();
        List<CBaseObject> lstObj= WorkflowDef.getActivesDefMgr().GetList();
        //按序号排序
        Map<Integer, CActivesDef> sortObj = new HashMap<Integer, CActivesDef>();
        for (CBaseObject obj : lstObj)
        {
            CActivesDef ActivesDef = (CActivesDef)obj;
            sortObj.put(ActivesDef.getIdx(), ActivesDef);
        }
        CActivesDef SuccessActivesDef = null;
        CActivesDef FailureActivesDef = null;

        String sData = "";
        for (Integer key : sortObj.keySet())
        {
            CActivesDef ActivesDef = sortObj.get(key);
            if (ActivesDef.getWType() == ActivesType.Success)
            {
                SuccessActivesDef = ActivesDef;
                continue;
            }
            if (ActivesDef.getWType() == ActivesType.Failure)
            {
                FailureActivesDef = ActivesDef;
                continue;
            }
            CUser User = (CUser)Global.GetCtx(this.getServletContext()).getUserMgr().Find(ActivesDef.getB_User_id());
            CRole Role = (CRole)Global.GetCtx(this.getServletContext()).getCompanyMgr().FindTopCompany().getRoleMgr().Find(ActivesDef.getB_Role_id());
            String AType="", UserName = "", RoleName = "";
            AType = ActivesDef.getAType();
            UserName = (User != null) ? User.getName() : "";
            RoleName = (Role != null) ? Role.getName() : "";

            sData += String.format("{ \"id\": \"%s\",\"Name\":\"%s\", \"Idx\":\"%d\", \"WType\":\"%d\", \"AType\":\"%s\", \"UserName\":\"%s\", \"RoleName\":\"%s\" },"
                , ActivesDef.getId().toString()
                , ActivesDef.getName()
                , ActivesDef.getIdx()
                , ActivesDef.getWType().ordinal()
                , AType
                , UserName
                , RoleName);
        }

        //成功/失败结束活动放最后
        if (SuccessActivesDef != null)
        {
            sData += String.format("{ \"id\": \"%s\",\"Name\":\"%s\", \"Idx\":\"%d\", \"WType\":\"%d\", \"B_User_id\":\"%s\", \"UserName\":\"%s\" },"
                , SuccessActivesDef.getId().toString()
                , SuccessActivesDef.getName()
                , SuccessActivesDef.getIdx()
                , SuccessActivesDef.getWType().ordinal()
                , SuccessActivesDef.getB_User_id().toString()
                , "");
        }
        if (FailureActivesDef != null)
        {
            sData += String.format("{ \"id\": \"%s\",\"Name\":\"%s\", \"Idx\":\"%d\", \"WType\":\"%d\", \"B_User_id\":\"%s\", \"UserName\":\"%s\" },"
                , FailureActivesDef.getId().toString()
                , FailureActivesDef.getName()
                , FailureActivesDef.getIdx()
                , FailureActivesDef.getWType().ordinal()
                , FailureActivesDef.getB_User_id().toString()
                , "");
        }

        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, lstObj.size());

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void GetLinkData()
    {
        String ActivesId = request.getParameter("ActivesId");
        if (Global.IsNullParameter(ActivesId))
        {
            return;
        }
        UUID guidActivesId = Util.GetUUID(ActivesId);

        CWorkflowDef WorkflowDef = GetWorkflowDef();
        List<CBaseObject> lstObj = WorkflowDef.getLinkMgr().GetList();

        String sData = "";
        int iCount = 0;
        for (CBaseObject obj : lstObj)
        {
            CLink Link = (CLink)obj;
            if (!Link.getPreActives().equals(guidActivesId))
                continue;
            CActivesDef next = (CActivesDef)WorkflowDef.getActivesDefMgr().Find(Link.getNextActives());

            sData += String.format("{ \"id\": \"%s\",\"Result\":\"%d\",\"ResultName\":\"%s\", \"Condiction\":\"%s\", \"NextActives\":\"%s\", \"NextActivesName\":\"%s\"},"
                , Link.getId().toString()
                , Link.getResult().ordinal()
                ,(Link.getResult()== enumApprovalResult.Accept)?"接受":"拒绝"
                , Link.getCondiction()
                , Link.getNextActives().toString()
                ,(next!=null)?next.getName():"");
            iCount++;
        }
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, iCount);

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    void DeleteActivesDef()
    {
        String delid = request.getParameter("delid");
        if (Global.IsNullParameter(delid))
        {
        	try {
				response.getWriter().print("请选择活动！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return;
        }
        GetWorkflowDef().getActivesDefMgr().Delete(Util.GetUUID(delid));
    }
    void SelectTable()
    {
        String Table_id = request.getParameter("Table_id");
        GetWorkflowDef().setFW_Table_id ( Util.GetUUID(Table_id));
    }

    void DeleteLink()
    {
        String delid = request.getParameter("delid");
        if (Global.IsNullParameter(delid))
        {
        	try {
				response.getWriter().print("请选择连接！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return;
        }
        GetWorkflowDef().getLinkMgr().Delete(Util.GetUUID(delid));
    }
    void PostData()
    {
		try {
			String Name = request.getParameter("Name");
			String Catalog_id = request.getParameter("Catalog_id");
			String Table_id = request.getParameter("Table_id");

			if (Global.IsNullParameter(Name)) {
				response.getWriter().print("名称不能空！");
				return;
			}
			if (Global.IsNullParameter(Table_id)) {
				response.getWriter().print("请选择表对象！");
				return;
			}

			if (m_Company.getWorkflowDefMgr().FindByName(Name) != null) {
				response.getWriter().print("相同名称的工作流已经存在！");
				return;
			}
			GetWorkflowDef().setName(Name);
			if (Catalog_id .length()>0)
				GetWorkflowDef().setWF_WorkflowCatalog_id(
						Util.GetUUID(Catalog_id));
			GetWorkflowDef().setFW_Table_id(Util.GetUUID(Table_id));

			m_Company.getWorkflowDefMgr().AddNew(GetWorkflowDef());

			if (!m_Company.getWorkflowDefMgr().Save(true)) {
				response.getWriter().print("添加失败！");
				return;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

	public CWorkflowDef GetWorkflowDef()
	{
	    if (request.getSession().getAttribute("AddWorkflowDef") == null)
	    {
	        CUser user = (CUser)request.getSession().getAttribute("User");
	        CWorkflowDef WorkflowDef = new CWorkflowDef();
	        WorkflowDef.Ctx = Global.GetCtx(this.getServletContext());
	        UUID Catalog_id = Util.GetEmptyUUID();
	        if (!Global.IsNullParameter(request.getParameter("catalog_id")))
	            Catalog_id = Util.GetUUID(request.getParameter("catalog_id"));
	        WorkflowDef.setWF_WorkflowCatalog_id ( Catalog_id);
	        WorkflowDef.setB_Company_id ( Util.GetUUID(request.getParameter("B_Company_id")));
	        WorkflowDef.setCreator (user.getId());
	        CActivesDef startActivesDef = new CActivesDef();
	        startActivesDef.Ctx = Global.GetCtx(this.getServletContext());
	        startActivesDef.setWF_WorkflowDef_id ( WorkflowDef.getId());
	        startActivesDef.setWType ( ActivesType.Start);
	        startActivesDef.setName ( "启动");
	        startActivesDef.setIdx ( 0);
	        startActivesDef.setCreator ( user.getId());
	        WorkflowDef.getActivesDefMgr().AddNew(startActivesDef);
	
	        CActivesDef SuccessActivesDef = new CActivesDef();
	        SuccessActivesDef.Ctx = Global.GetCtx(this.getServletContext());
	        SuccessActivesDef.setWF_WorkflowDef_id( WorkflowDef.getId());
	        SuccessActivesDef.setWType ( ActivesType.Success);
	        SuccessActivesDef.setName ( "成功结束");
	        SuccessActivesDef.setIdx ( -1);
	        SuccessActivesDef.setCreator ( user.getId());
	        WorkflowDef.getActivesDefMgr().AddNew(SuccessActivesDef);
	
	        CActivesDef FailureActivesDef = new CActivesDef();
	        FailureActivesDef.Ctx = Global.GetCtx(this.getServletContext());
	        FailureActivesDef.setWF_WorkflowDef_id ( WorkflowDef.getId());
	        FailureActivesDef.setWType ( ActivesType.Failure);
	        FailureActivesDef.setName ( "失败结束");
	        FailureActivesDef.setIdx ( -2);
	        FailureActivesDef.setCreator ( user.getId());
	        WorkflowDef.getActivesDefMgr().AddNew(FailureActivesDef);
	
	        CLink Link = new CLink();
	        Link.Ctx = Global.GetCtx(this.getServletContext());
	        Link.setWF_WorkflowDef_id ( WorkflowDef.getId());
	        Link.setResult ( enumApprovalResult.Accept);
	        Link.setPreActives (startActivesDef.getId());
	        Link.setNextActives (SuccessActivesDef.getId());
	        Link.setCreator (user.getId());
	        WorkflowDef.getLinkMgr().AddNew(Link);
	
	        request.getSession().setAttribute("AddWorkflowDef", WorkflowDef);
	    }
	    return (CWorkflowDef)request.getSession().getAttribute("AddWorkflowDef");
	}
}
